package com.zjy.service.impl;

import com.zjy.bean.Goods;
import com.zjy.bean.Order;
import com.zjy.bean.ShoppingCart;
import com.zjy.dao.GoodsMapper;
import com.zjy.dao.OrderMapper;
import com.zjy.dao.ShoppingCartMapper;
import com.zjy.dto.ListResponse;
import com.zjy.dto.OrderDTO;
import com.zjy.dto.OrderParam;
import com.zjy.dto.OrderQTO;
import com.zjy.service.OrderService;
import com.zjy.utils.ObjectUtils;
import com.zjy.utils.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2019/5/20.
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private GoodsMapper goodsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addOrder(OrderDTO orderDTO) {
        //插入订单表，订单状态为待付款
        String orderId = UUIDUtils.getUUID();
        Order order = orderDTO.getOrder();
        order.setId(orderId);
        order.setStatus(0);
        orderMapper.insertSelective(order);

        //更新购物车的orderId，将购物车删除
        List<String> shoppingCartIdList = orderDTO.getShoppingCartIdList();
        if(!ObjectUtils.isNullOrEmpty(shoppingCartIdList)){
            for (String s : shoppingCartIdList) {
                ShoppingCart sc = shoppingCartMapper.selectById(s);
                if(!ObjectUtils.isNullOrEmpty(sc)){
                    //设置订单id、软删购物车
                    sc.setOrderId(orderId);
                    sc.setDelFlag(1);
                    shoppingCartMapper.updateByPrimaryKeySelective(sc);

                    //减少商品库存
                    int quantity = sc.getQuantity();
                    String goodsId = sc.getGoodsId();
                    Goods goods = goodsMapper.selectGoodsById(goodsId);
                    if(goods != null){
                        goods.setStockNum(goods.getStockNum() - quantity);
                        //增加销售量
                        goods.setSaleNum(goods.getSaleNum() + quantity);
                        goodsMapper.updateByPrimaryKeySelective(goods);
                    }
                }
            }
        }
        return orderId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOrderById(List<String> idList) {
        return orderMapper.deleteOrderById(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deliverOrder(String orderId) {
        int count = 0;
        Order order = orderMapper.selectByOrderId(orderId);
        if(!ObjectUtils.isNullOrEmpty(order)){ //修改订单状态为已发货：2 ，生成订单号
            String orderNo = UUIDUtils.getOrderNoByUUId();
            order.setOrderNo(orderNo);
            order.setStatus(2);
            count = orderMapper.updateByPrimaryKeySelective(order);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int payOrder(String orderId) {
        int count = 0;
        Order order = orderMapper.selectByOrderId(orderId);
        if(!ObjectUtils.isNullOrEmpty(order)){ //修改订单状态为代发货：1
            order.setStatus(1);
            count = orderMapper.updateByPrimaryKeySelective(order);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int completeOrder(String orderId) {
        int count = 0;
        Order order = orderMapper.selectByOrderId(orderId);
        if(!ObjectUtils.isNullOrEmpty(order)){ //修改订单状态已完成：3
            order.setStatus(3);
            count = orderMapper.updateByPrimaryKeySelective(order);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderQTO selectOrderById(String orderId) {
        OrderQTO orderQTO = new OrderQTO();
        Order order = orderMapper.selectByOrderId(orderId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectShopCartByOrderId(orderId);
        if(!ObjectUtils.isNullOrEmpty(order)){
            orderQTO.setOrder(order);
        }
        if(!ObjectUtils.isNullOrEmpty(shoppingCartList)){
            orderQTO.setShoppingCartList(shoppingCartList);
        }
        return orderQTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ListResponse selectOrderList(OrderParam orderParam) {
//        List<OrderQTO> orderQTOList = new ArrayList<>();
//        List<Order> orderList = orderMapper.selectOrderList(orderParam);//获取符合条件的订单列表
//        if(!ObjectUtils.isNullOrEmpty(orderList)){  //遍历列表，查询出购物车，拼接成OrderQTO
//            for (Order order : orderList) {
//                OrderQTO orderQTO = new OrderQTO();
//                List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectShopCartByOrderId(order.getId());
//                if(!ObjectUtils.isNullOrEmpty(order)){
//                    orderQTO.setOrder(order);
//                }
//                if(!ObjectUtils.isNullOrEmpty(shoppingCartList)){
//                    orderQTO.setShoppingCartList(shoppingCartList);
//                }
//                orderQTOList.add(orderQTO);
//            }
//        }
//
//        return orderQTOList;
        ListResponse response = new ListResponse();
        List<OrderQTO> orderQTOList = new ArrayList<>();
        double pageSize = orderParam.getPageSize(); //获取页面大小
        int totalCount = orderMapper.getOrderCount(orderParam);  //获取总条数
        int totalPage = 0;
        if(pageSize > 0){
            totalPage = (int)Math.ceil((double)totalCount/pageSize); //计算总页数，结果向上取整
        }
        List<Order> orderList = orderMapper.selectOrderList(orderParam);//获取符合条件的订单列表
        if(!ObjectUtils.isNullOrEmpty(orderList)) {  //遍历列表，查询出购物车，拼接成OrderQTO
            for (Order order : orderList) {
                OrderQTO orderQTO = new OrderQTO();
                List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectShopCartByOrderId(order.getId());
                if (!ObjectUtils.isNullOrEmpty(order)) {
                    orderQTO.setOrder(order);
                }
                if (!ObjectUtils.isNullOrEmpty(shoppingCartList)) {
                    orderQTO.setShoppingCartList(shoppingCartList);
                }
                orderQTOList.add(orderQTO);
            }
        }
        response.setData(orderQTOList);
        response.setPageNum(orderParam.getPageNum());
        response.setPageSize(orderParam.getPageSize());
        response.setTotalCount(totalCount);
        response.setTotalPage(totalPage);
        return  response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Object> getOrderData() {
        HashMap<String,Object> map = new HashMap<>();
        //获取今日订单数、订单总数、今日销售额
        Integer totalCount = orderMapper.selectOrderTotalCount();
        Integer todayCount = 0;
        BigDecimal todayAmount = BigDecimal.ZERO.setScale(2);
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");//今天零点
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当前时间
        String begin = dateFormat1.format(date) + " 00:00:00";
        String now = dateFormat2.format(date);
        List<Order> orderList = orderMapper.selectOrderTodayCount(begin,now);

        if(orderList != null){
            todayCount = orderList.size();
            if(orderList.size() > 0){
                for (Order order : orderList) {
                    todayAmount = todayAmount.add(order.getTotalAmount());        //计算今日销售额
                }
            }
        }
        map.put("totalCount",totalCount);
        map.put("todayCount",todayCount);
        map.put("todayAmount",todayAmount);
        return map;
    }
}
